<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function soil_info_list_page()
{
    @$output = drupal_render(drupal_get_form('soil_info_list_form'));
    return $output;
}

function soil_info_list_form($form, &$form_state)
{
    global $user;
    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
    }
    if(!empty($form_state['addr_id'])){
        $form['#addr_id'] = $form_state['addr_id'];
    }
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if(!empty($form_state['farmer'])){
        $form['#farmer'] = $form_state['farmer'];
    }


    $user_info = _get_user_info($user->uid);
    $init_year = !empty($form_state['values']['year']) ? $form_state['values']['year'] : '';
    _insert_date_selection_form($form, $form_state, 5, $init_year, '', false);
    if ($user_info['role'] != '农户') {
        if(empty($form_state['farmer'])&& empty($form['#addr_id'])){
            $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
            $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state), '', '');
        }
        $form['sampler'] = array(
            '#attributes' => array('placeholder' => '送样人'),
            '#title_display' => 'before',
            '#type' => 'textfield',
            '#default_value' => !empty($form_state['values']['sampler']) ? $form_state['values']['sampler'] : '',
            '#id'=>'sampler'
        );
        if(!empty($_GET['special_activities'])){
            $special_activities_title = get_special_activities_title($_GET['special_activities']);
        }
        $form['special_activities'] = array(
            '#type' => 'textfield',
            '#title' => '专项活动',
            '#size' => 32,
            '#maxlength' => 50,
            '#id'=>'special_activities_textfield',
            '#default_value' => $special_activities_title,
        );
    }
    $fields = array(
        '' => '请选择',
        'nitrogen' => '氮',
        'phosphorus' => '磷',
        'potassium' => '钾',
        'organicmatter' => '有机质',
        'ph' => 'PH值',
        'calcium' => '钙',
        'magnesium' => '镁',
        'sulfur' => '硫',
        'zinc' => '锌',
        'copper' => '铜',
        'iron' => '铁',
        'boron' => '硼',
        'manganese' => '锰',
    );
    numerical_range_search($form, $fields);
    $table['#markup'] = data_list_view_page($form, $form_state);
    ajax_submit_form($form, $form_state, $table, '');
    return $form;
}

function soil_info_list_form_validate($form, &$form_state)
{
}

function data_list_view_page(&$form = '', &$form_state = '')
{
    global $user;
    $user_info = _get_user_info($user->uid);
    //表头
    if ($user_info['role'] === '农户') {
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            array('data' => '送样人', 'class' => ['essential sampler']),
            array('data' => '采样日期', 'class' => ['integrant essential date'], 'field' => 'sample_date'),
            array('data' => '操作', 'class' => ['essential more']),
        );
    } else {
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            array('data' => '送样人', 'class' => ['essential sampler']),
            array('data' => '采样日期', 'class' => ['integrant essential date'], 'field' => 'sample_date'),
            isset($form_state['addr_id']) && !empty($form_state['addr_id'])?"":
            array('data' => '地址', 'class' => ['essential province city county']),
            isset($form_state['farmer']) && !empty($form_state['farmer']) ? "" :
                array('data' => '农户', 'class' => ['integrant essential farmer_name'], 'field' => 'farmer_name'),
            array('data' => '操作', 'class' => ['essential more']),
        );
    }
    $output = '';
    $query = db_select('soil_info', 'I')->extend('PagerDefault')->extend('TableSort');
    $query->leftjoin('farmer', 'F', 'F.farmer_id=I.farmer_id');
    $query->fields('I');
    $query->addField('F', 'farmer_name');
    $query->addField('F', 'addr_id');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');


        $datestr = '';
        if (!empty($form_state['values']['year'])) {//查询条件
            if ($form_state['values']['year']) {
                $datestr .= $form_state['values']['year'] . '-';
            }
        }
        if ($datestr) {
            $query->condition('I.sample_date', db_like($datestr) . '%', 'LIKE');
        }
    if ($user_info['role'] === '农户') {
        $query->condition('I.farmer_id', $user->uid);
    } else {
        //地址级别查询
        _address_search_conditon($query,$form_state);
        if (!empty($form_state['values']['farmer'])) {
            $query->condition('I.farmer_id', $form_state['values']['farmer']);
        }
        if (!empty($form_state['values']['sampler'])) {
            $query->condition('I.sampler', '%' . db_like($form_state['values']['sampler']) . '%', 'LIKE');
        }
        if (!empty($_GET['farmer_id'])) {
            $query->condition('I.farmer_id', $_GET['farmer_id']);
            $form_state['farmer'] = $_GET['farmer_id'];
        }
        if (!empty($form_state['farmer'])) {//
            $query->condition('I.farmer_id', $form_state['farmer'], '=');
        }
        if (!empty($form_state['addr_id'])) {//
            $query->condition('F.addr_id', $form_state['addr_id'], '=');
        }
        if (!empty($form_state['values']['farmer_id'])) {//
            $query->condition('I.farmer_id', $form_state['values']['farmer_id'], '=');
        }
        if(!user_access('view all soil_info') && user_access('view own soil_info')){
            $query->condition('I.author_uid',$user->uid, '=');
        }
        //专项活动
        if(!empty($form_state['values']['special_activities'])){
            $special_activities_id = get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities'],false);
            if(!empty($special_activities_id)){
                $query->condition('I.special_activities_id',$special_activities_id, '=');
            }else{
                $query->condition('I.special_activities_id',0, '=');
            }
        }
    }
    if(!empty($_GET['special_activities'])){
        $query->condition('I.special_activities_id',$_GET['special_activities'], '=');
    }
    if (!empty($form_state['values']['field'])) {
        if (!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])) {
            $db_and = db_and();
            $db_and->condition('I.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
            $db_and->condition('I.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($form_state['values']['min_number'])) {
            $query->condition('I.' . $form_state['values']['field'], $form_state['values']['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('I.' . $form_state['values']['field'], $form_state['values']['max_number'], '<');
        }
    }
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');
    $query->addField('F', 'farmer_id');
    //统计
    $statQuery = $query->cloneQuery();
    $statQuery->addExpression('format(avg(I.nitrogen),2)','avg_nitrogen');
    $statQuery->addExpression('format(avg(I.phosphorus),2)','avg_phosphorus');
    $statQuery->addExpression('format(avg(I.potassium),2)','avg_potassium');
    $statQuery->addExpression('format(avg(I.organicmatter),2)','avg_organicmatter');
    $statQuery->addExpression('format(avg(I.ph),2)','avg_ph');
    $statQuery->addExpression('format(avg(I.calcium),2)','avg_calcium');
    $statQuery->addExpression('format(avg(I.magnesium),2)','avg_magnesium');
    $statQuery->addExpression('format(avg(I.sulfur),2)','avg_sulfur');
    $statQuery->addExpression('format(avg(I.zinc),2)','avg_zinc');
    $statQuery->addExpression('format(avg(I.copper),2)','avg_copper');
    $statQuery->addExpression('format(avg(I.iron),2)','avg_iron');
    $statQuery->addExpression('format(avg(I.boron),2)','avg_boron');
    $statQuery->addExpression('format(avg(I.manganese),2)','avg_manganese');
    $statQuery->addExpression('count(*)','count');
    $statInfo = $statQuery->execute()->fetchObject();
    $form['#stat']['#count'] = $statInfo->count;
    $form['#stat']['#avg_nitrogen'] = $statInfo->avg_nitrogen;
    $form['#stat']['#avg_phosphorus'] = $statInfo->avg_phosphorus;
    $form['#stat']['#avg_potassium'] = $statInfo->avg_potassium;
    $form['#stat']['#avg_organicmatter'] = $statInfo->avg_organicmatter;
    $form['#stat']['#avg_ph'] = $statInfo->avg_ph;
    $form['#stat']['#avg_calcium'] = $statInfo->avg_calcium;
    $form['#stat']['#avg_magnesium'] = $statInfo->avg_magnesium;
    $form['#stat']['#avg_sulfur'] = $statInfo->avg_sulfur;
    $form['#stat']['#avg_zinc'] = $statInfo->avg_zinc;
    $form['#stat']['#avg_copper'] = $statInfo->avg_copper;
    $form['#stat']['#avg_iron'] = $statInfo->avg_iron;
    $form['#stat']['#avg_boron'] = $statInfo->avg_boron;
    $form['#stat']['#avg_manganese'] = $statInfo->avg_manganese;

    if(empty($form_state['values']) || empty($form_state['values']['order'])) {
        $query->orderBy('I.timestamp', 'DESC');
    }

    $query->limit(variable_get("list_page_item_number", 5));
    $soil_infoInfo = $query->orderByHeader($header)->execute();

    $rows = array();
    //表内容
    $n = 1;
    if ($user_info['role'] === '农户') {
        foreach ($soil_infoInfo as $row) {
            if (nonghua_user_access('soil_info', 'delete', $row->soil_info_id, $row->author_uid, $row->farmer_id)) {
                $disabled = ' class="listViewTableCheck" ';
            } else{
                $disabled = ' disabled="true" ';
            }
            $rows[] = array(
                array('data' => '<input type="checkbox"'.$disabled.' value ="' . $row->soil_info_id . '"/>' . $n++, 'class' => ['integrant essential no']),
                array('data' => $row->sampler, 'class' => ['integrant essential sampler']),
                array('data' => $row->sample_date, 'class' => ['integrant essential date']),
                isset($form_state['farmer']) && !empty($form_state['farmer']) ?
                    array('data' => '<a href="' . base_path() . 'farmer/soil_info/edit/' . $row->soil_info_id . '?farmer_id='.$form_state['farmer'].'" data-toggle="modal" target="_blank"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more') :
                    array('data' => '<a href="' . base_path() . 'farmer/soil_info/edit/' . $row->soil_info_id . '" data-toggle="modal" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            );
        }
    } else {
        foreach ($soil_infoInfo as $row) {
            $city = $row->city ? ' ' . $row->city : '';
            $county = $row->county ? ' ' . $row->county : '';
            $town = $row->town ? ' ' . $row->town : '';
            $village = $row->village ? ' ' . $row->village : '';

            if (nonghua_user_access('soil_info', 'delete', $row->soil_info_id, $row->author_uid, $row->farmer_id)) {
                $disabled = ' class="listViewTableCheck" ';
            } else{
                $disabled = ' disabled="true" ';
            }

            $rows[] = array(
                array('data' => '<input type="checkbox"'.$disabled.' value ="' . $row->soil_info_id . '"/>' . $n++, 'class' => ['integrant essential no']),
                array('data' => $row->sampler, 'class' => ['essential sampler']),
                array('data' => $row->sample_date, 'class' => ['integrant goRight essential date']),
                isset($form_state['addr_id']) && !empty($form_state['addr_id'])?"":
                array('data' => $row->province . $city . $county.$town.$village, 'class' => ['integrant essential province city county']),
                isset($form_state['farmer']) && !empty($form_state['farmer']) ? "" :
                    array('data' => '<a href="' . base_path() . 'farmer/edit/' . $row->farmer_id . '?farmer_id='.$row->farmer_id.'">' . $row->farmer_name . '</a>', 'class' => ['integrant integrant haveTobr essential far_name']),
                (isset($form_state['farmer']) && !empty($form_state['farmer']))||(isset($form_state['addr_id']) && !empty($form_state['addr_id']))?
                    array('data' => '<a href="' . base_path() . 'farmer/soil_info/edit/' . $row->soil_info_id .'?'.
                        (isset($form_state['addr_id']) && !empty($form_state['addr_id'])?'addr_id='.$form_state['addr_id'].'&':'').
                        (isset($form_state['farmer']) && !empty($form_state['farmer'])?'farmer_id='.$form_state['farmer']:'').
                        '" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>','class' => 'essential more'):
                    array('data' => '<a href="' . base_path() . 'farmer/soil_info/edit/' . $row->soil_info_id . '" data-toggle="modal" target="_self"><img width="15px" height="15px" src="' . base_path() . 'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            );
        }
    }
    $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
    /*	 * *按钮** */
    if (sizeof($rows) > 0 && (user_access('delete own soil_info') ||  user_access('delete all soil_info'))) {
        $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
        $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
    }
    if(!empty($form_state['values']['village'])){
        $addr_id = $form_state['values']['village'];
        $str = 'village=';
    }elseif(!empty($form_state['values']['town'])){
        $addr_id = $form_state['values']['town'];
        $str = 'town=';
    }elseif(!empty($form_state['values']['county'])){
        $addr_id = $form_state['values']['county'];
        $str = 'county=';
    }elseif(!empty($form_state['values']['city'])){
        $addr_id = $form_state['values']['city'];
        $str = 'city=';
    }elseif(!empty($form_state['values']['province'])){
        $addr_id = $form_state['values']['province'];
        $str = 'province=';
    }
    $str .= $addr_id;
    $output .= '<a href="'.base_path().'farmer/soil_info/export?' .$str.'&sampler='.$form_state['values']['sampler'].'&year='.$form_state['values']['year'].'&field='.$form_state['values']['field'].'&min_number='.$form_state['values']['min_number'].'&max_number='.$form_state['values']['max_number'].'" data-toggle="modal" class="btn btn-mini">导出</a>';
    $output .= theme('pager');
    return $output;
}

function soil_info_delete()
{
    //todo: delete fertilizer_recommendation with this soil_info_id
    ajax_table_delete('soil_info', 'soil_info_id');
}


function soil_info_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('农户','农户电话','地址','送样人','采样日期','氮',
        '磷',
        '钾',
        '有机质',
        'PH值',
        '钙',
        '镁',
        '硫',
        '锌',
        '铜',
        '铁',
        '硼',
        '锰',);
    $data = get_soil_info_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'土壤信息数据');
}

function get_soil_info_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('soil_info', 'I');
    $query->leftjoin('farmer', 'F', 'F.farmer_id=I.farmer_id');
    $query->addField('F', 'farmer_name');
    $query->addField('F', 'cell');
    $query->join('addr', 'A', 'A.addr_id=F.addr_id');
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    $query->leftJoin('addr', 'A4', 'A.town_id=A4.addr_id');
    $datestr = '';
    if (!empty($form_state['values']['year'])) {//查询条件
        if ($form_state['values']['year']) {
            $datestr .= $form_state['values']['year'] . '-';
        }
    }
    if ($datestr) {
        $query->condition('I.sample_date', db_like($datestr) . '%', 'LIKE');
    }
    if ($user_info['role'] === '农户') {
        $query->condition('I.farmer_id', $user->uid);
    } else {
        if (!empty($_GET['village'])) {//乡镇级
            $query->condition('A.village_id', $_GET['village'], '=');
        } elseif (!empty($_GET['town'])) {//乡镇级
            $query->condition('A.town_id', $_GET['town'], '=');
        } elseif (!empty($_GET['county'])) {//县级
            $query->condition('A.county_id',$_GET['county'], '=');
        } elseif (!empty($_GET['city'])) {//市级
            $query->condition('A.city_id', $_GET['city'], '=');
        } elseif (!empty($_GET['province'])) {//省级
            $query->condition('A.province_id', $_GET['province'], '=');
        }
        if (!empty($form_state['values']['farmer'])) {
            $query->condition('I.farmer_id', $_GET['farmer']);
        }
        if (!empty($form_state['values']['sampler'])) {
            $query->condition('I.sampler', '%' . db_like($_GET['sampler']) . '%', 'LIKE');
        }
        if (!empty($_GET['farmer_id'])) {
            $query->condition('I.farmer_id', $_GET['farmer_id']);
            $form_state['farmer'] = $_GET['farmer_id'];
        }
        if (!empty($form_state['farmer'])) {//
            $query->condition('I.farmer_id', $_GET['farmer'], '=');
        }
        if (!empty($form_state['addr_id'])) {//
            $query->condition('F.addr_id', $_GET['addr_id'], '=');
        }
        if (!empty($form_state['values']['farmer_id'])) {//
            $query->condition('I.farmer_id',$_GET['farmer_id'], '=');
        }
        if(!user_access('view all soil_info') && user_access('view own soil_info')){
            $query->condition('I.author_uid',$user->uid, '=');
        }
    }
    if (!empty($_GET['field'])) {
        if (!empty($_GET['min_number']) && !empty($_GET['max_number'])) {
            $db_and = db_and();
            $db_and->condition('I.' . $_GET['field'], $_GET['min_number'], '>');
            $db_and->condition('I.' . $_GET['field'], $_GET['max_number'], '<');
            $query->condition($db_and);
        } elseif (!empty($_GET['min_number'])) {
            $query->condition('I.' .$_GET['field'], $_GET['min_number'], '>');
        } elseif (!empty($form_state['values']['max_number'])) {
            $query->condition('I.' .$_GET['field'],$_GET['max_number'], '<');
        }
    }
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->addField('A4', 'name', 'town');
    $query->addField('A', 'name', 'village');

    $query->fields('I',array('sampler','sample_date','nitrogen' , 'phosphorus', 'potassium', 'organicmatter', 'ph', 'calcium', 'magnesium', 'sulfur', 'zinc', 'copper', 'iron', 'boron', 'manganese'));
    if(empty($form_state['values'])) {
        $query->orderBy('I.timestamp', 'DESC');
    }

    $soil_infoInfo = $query->execute()->fetchAll();
    foreach($soil_infoInfo as $k => $v){
        $soil_infoInfo[$k]->province= $v->province.$v->city.$v->county.$v->town.$v->village;
        unset($soil_infoInfo[$k]->city);
        unset($soil_infoInfo[$k]->county);
        unset($soil_infoInfo[$k]->town);
        unset($soil_infoInfo[$k]->village);
    }
    return $soil_infoInfo;
}